import React from 'react';
import './App.css';
import { RouterProvider } from 'react-router-dom'
import {staticRoutes} from './router'
import GeneratesRoutes  from '@/utils/generatesRoutes'
import { useEffect,useState,Suspense} from 'react';
import { createBrowserRouter } from 'react-router-dom';
import { getMenu } from '@/api/users';
import { useDispatch } from 'react-redux';
import { setMenuList } from '@/store/login/authSlice'
import { useSelector } from 'react-redux';

function App() {
  const [routers,setRouters] = useState<any>(null)
  const dispatch = useDispatch()
  const {token} = useSelector((state:any)=>state.authSlice)
  
  useEffect(()=>{
    async function loadData() {
      const {data} =  await getMenu()
      if(data.length){
        dispatch(setMenuList(data))
        const routers=GeneratesRoutes(data)
        const myRoutess = [...staticRoutes]
        myRoutess[0].children = routers
          myRoutess[0].children[0].index = true
        // setRouters(myrouter)
        const router = createBrowserRouter(myRoutess)
        setRouters(router)
      }else{
        const router = createBrowserRouter(staticRoutes)
        setRouters(router)
      }
    }
    loadData()

  },[token]) // 没有这个依赖项，那么就拿不到数据，因为是异步的，数据还没有回来，App.tsx你就提前请求了

  if(routers){
    return (
      <div className="App">
        <Suspense fallback={<p>加载中....</p>}>
          <RouterProvider router={routers}></RouterProvider>
        </Suspense>
      </div>
    );
  }else{
    return <div>你再等等吧</div>
  }
}

export default App;
